package com.qf.work0625.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;


@RestController
@RequestMapping("/")
public class VoteController {
    private static final String REDIS_HOST = "172.16.1.115";  // Redis服务器地址
    private static final int REDIS_PORT = 6379;  // Redis服务器端口号
    private static final int VOTE_DURATION = 60;  // 投票有效期（秒）
    private static final String VOTE_PREFIX = "vote:";  // Redis键名前缀

    @GetMapping("/vote")
    public String vote(String candidateName, String phoneNumber){
        Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT);
        String candidateKey = VOTE_PREFIX + candidateName;
        String phoneKey = VOTE_PREFIX + phoneNumber;
        String lockKey = VOTE_PREFIX + candidateName + ":lock";
        String result = null;
        if (jedis.exists(phoneKey)){
            result = "{\"msg\":\"error\",\"code\":0,\"data\":\"该手机号已投票\"}";
        }else {
            SetParams params = new SetParams().nx().ex(VOTE_DURATION);
            String lockResult = jedis.set(lockKey,"locked",params);
            if (lockResult!=null){
                //更新候选人得票数
                jedis.incr(candidateKey);
                jedis.set(phoneKey, "voted", new SetParams().ex(VOTE_DURATION));
                long totalNum = jedis.getSet(candidateKey, "0") == null ? 0 : Long.parseLong(jedis.get(candidateKey));
                result = "{\"msg\":\"OK\",\"code\":1,\"data\":{\"candidateName\":\"" + candidateName + "\",\"totalnum\":" + totalNum + "}}";
                jedis.del(lockKey);
            }else {
                result = "{\"msg\":\"error\",\"code\":0,\"data\":\"投票失败，请稍后再试\"}";
            }
        }
        return result;
    }

}
